package com.zh.controller;

import com.alibaba.fastjson.JSON;
import com.zh.comm.AlipayConfig;
import com.zh.comm.Params;
import com.zh.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private LoginService service;

    @RequestMapping("/toLogin")
    public String toLogin(){

        return "/view/login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Map login(ServletRequest request, HttpSession session) {
        Map param = Params.getParam(request);
        List<Map> list = service.login(param);
        Map resultMap = new HashMap();
        if (!list.isEmpty() && list.size() == 1) {
            if("1".equals(list.get(0).get("state"))){
                resultMap.put("success", true);
                resultMap.put("user", list.get(0));
                AlipayConfig.setUid(list.get(0).get("uid").toString());
                session.setAttribute("user", list.get(0));
            }else{
                resultMap.put("success", false);
                resultMap.put("msg", "登录失败，该用户已被禁用，请联系管理员！！！");
            }

        } else {
            resultMap.put("success", false);
            resultMap.put("msg", "登录失败，用户名或密码错误");
        }

        return resultMap;
    }

    @RequestMapping("/toRegister")
    public String toRegister() {
        return "view/register";
    }

    @RequestMapping("/register")
    @ResponseBody
    public Map register(ServletRequest request) {
        Map param = Params.getParam(request);
        param.put("type", "2"); // 管理员
        int rtn = service.register(param);
        Map resultMap = new HashMap();
        resultMap.put("success", true);
        return resultMap;
    }

    @RequestMapping("/checkUname")
    @ResponseBody
    public Map checkUname(ServletRequest request) {
        Map param = Params.getParam(request);
        int rtn = service.checkUname(param);
        Map resultMap = new HashMap();
        if (rtn != 0) {
            resultMap.put("success", false);
        } else {
            resultMap.put("success", true);
        }
        return resultMap;
    }

    @RequestMapping("/unlogin")
    public String unlogin(HttpServletRequest request){
        //销毁session
        request.getSession().invalidate();
        return "/view/login";
    }

    /**
     * 用户管理
     * @return
     */
    @RequestMapping(value = "userAdmin")
    public String userAdmin() {
        return "view/userAdmin";
    }
}
